package com.cait.dutyfree.action.admin;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.cait.dutyfree.common.Activation;
import com.cait.dutyfree.common.Mail;
import com.cait.dutyfree.dataaccess.UserServiceDAO;
import com.cait.dutyfree.pojo.LoginUser;
import com.cait.dutyfree.security.MD5Hash;
import com.cait.dutyfree.security.Validator;
import com.opensymphony.xwork2.ActionSupport;

public class UsersAction extends ActionSupport {
	// spring injection
	private UserServiceDAO userServiceDAO;

	public void setUserServiceDAO(UserServiceDAO userServiceDAO) {
		this.userServiceDAO = userServiceDAO;
	}

	// end spring injection

	// ======================================================= Users list
	List<LoginUser> users = new ArrayList<LoginUser>();

	public List<LoginUser> getUsers() {
		return users;
	}

	public void setUsers(List<LoginUser> users) {
		this.users = users;
	}

	public String usersIndex() throws Exception {
		this.setUsers(userServiceDAO.getUsers());
		return SUCCESS;
	}

	// ======================================================= end users list

	public String addUser() {
		return SUCCESS;
	}

	// ======================================================= add user

	public String getfName() {
		return fName;
	}

	public void setfName(String fName) {
		this.fName = fName;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getlName() {
		return lName;
	}

	public void setlName(String lName) {
		this.lName = lName;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getTeleNo() {
		return teleNo;
	}

	public void setTeleNo(String teleNo) {
		this.teleNo = teleNo;
	}

	public String getMobileNo() {
		return mobileNo;
	}

	public void setMobileNo(String mobileNo) {
		this.mobileNo = mobileNo;
	}

	public String getcPassword() {
		return cPassword;
	}

	public void setcPassword(String cPassword) {
		this.cPassword = cPassword;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	private String fName;
	private String username;
	private String password;
	private String email;
	private String lName;
	private String address;
	private String teleNo;
	private String mobileNo;
	private String cPassword;
	private String code;

	public String submitAddUser() {
		System.out.println("**********************************************");
		LoginUser user = new LoginUser();
		this.submitAddUserValidation();
		if (this.hasErrors()) {
			return INPUT;
		} else {
			user.setfName(getfName());
			user.setUsername(getUsername());
			user.setPassword(MD5Hash.getHashedPassword(getPassword()));
			user.setEmail(getEmail());
			user.setlName(getlName());
			user.setAddress(getAddress());
			user.setContactNo(getTeleNo());
			user.setMobileNo(getMobileNo());
			user.setCreatedDate(new Date());
			user.setStatus(0);
			user.setUserType("admin");
			try {
				userServiceDAO.addUser(user);
				Mail.sendAccountActivationMail(getEmail(), getfName(),
						Activation.generateLink(user.getUserId()));
				addActionMessage("User added successfully");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return SUCCESS;
		}
	}

	public void submitAddUserValidation() {
		if (getfName().trim().length() < 2) {
			addFieldError("fName",
					"First name should be more than 2 charactors");
		}

		if (!Validator.isValidPassword(getUsername(), getPassword(),
				getcPassword())) {
			addFieldError("password", "Passwords must be more than 8 letters");
			addFieldError("password", "Passwords is not containing a number");
			addFieldError("password",
					"Password should not contain the username");
			addFieldError("password",
					"Passwords is not containing a special char");
			addFieldError("password", "Passwords and confirmation are not same");
		}

		if (!Validator.isValidEmailAddress(getEmail())) {
			addFieldError("email", "Invalid email address");
		}

		if (getTeleNo().trim().length() != 0) {
			if (Validator.isValidTelNo(getTeleNo())) {
				// addFieldError("teleNo", "Invalid telephone number");
			}
		}

		if (getMobileNo().trim().length() != 0) {
			if (Validator.isValidTelNo(getMobileNo())) {
				// addFieldError("teleNo", "Invalid mobile number");
			}
		}

		if (getCode().trim().length() != 4) {
			addFieldError("code", "Code should be with 4 charactors");
		}

		try {
			Integer.parseInt(getCode());
		} catch (Exception e) {
			addFieldError("code", "Code should be numeric");
		}
		try {
			if (userServiceDAO.isUserAvailable(getUsername().trim())) {
				addFieldError("username", "Username already available");
			}
		} catch (Exception e) {
			addFieldError("username", "Username already available");
			e.printStackTrace();
		}
	}

	// =======================================================
	private Integer id;
	private LoginUser loginUser;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public LoginUser getLoginUser() {
		return loginUser;
	}

	public void setLoginUser(LoginUser loginUser) {
		this.loginUser = loginUser;
	}

	public String editUser() {
		try {
			this.setLoginUser(userServiceDAO.getUser(this.getId()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}

	public String submitEditUser() {
		try {
			this.setLoginUser(userServiceDAO.getUser(this.getId()));

			this.submitEditUserValidation();

			getLoginUser().setfName(getfName());
			getLoginUser().setEmail(getEmail());
			getLoginUser().setlName(getlName());
			getLoginUser().setAddress(getAddress());
			getLoginUser().setContactNo(getTeleNo());
			getLoginUser().setMobileNo(getMobileNo());
			getLoginUser().setLastModifyDate(new Date());

			if (this.hasErrors()) {
				return INPUT;
			} else {
				userServiceDAO.updateUser(getLoginUser());
				addActionMessage("User updated successfully !!!");
				return SUCCESS;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return INPUT;
		}
	}

	private void submitEditUserValidation() {
		try {
			getLoginUser().setCode(Integer.parseInt(getCode()));
		} catch (Exception e) {
			addFieldError("code", "Code should be numeric");
		}

		if (getfName().trim().length() < 2) {
			addFieldError("fName",
					"First name should be more than 2 charactors");
		}

		if (getCode().trim().length() != 4) {
			addFieldError("code", "Code should be with 4 charactors");
		}

		if (!Validator.isValidEmailAddress(getEmail())) {
			addFieldError("email", "Invalid email address");
		}
	}

	// =======================================================

	// ======================================================= view user

	public String viewUser() {
		try {
			this.setLoginUser(userServiceDAO.getUser(this.getId()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}

	// ======================================================= end view user
	
	// ======================================================= delete user
	public String deleteUser() {

		try {
			this.setLoginUser(userServiceDAO.getUser(this.getId()));
			getLoginUser().setStatus(2);
			userServiceDAO.updateUser(getLoginUser());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	// ======================================================= end delete user
	
	// ======================================================= activate user
	public String activateUser() {

		try {
			this.setLoginUser(userServiceDAO.getUser(this.getId()));
			getLoginUser().setStatus(0);
			userServiceDAO.updateUser(getLoginUser());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	// ======================================================= end activate user
	
	// ajax request to checkt he username availablity
	private InputStream inputStream;
	private String userNameToCheck;

	public String getUserNameToCheck() {
		return userNameToCheck;
	}

	public void setUserNameToCheck(String userNameToCheck) {
		this.userNameToCheck = userNameToCheck;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public String ajaxCheckUsernameAvailablity() throws Exception {
		System.out.println("username to check:" + this.getUserNameToCheck());
		if (!userServiceDAO.isUserAvailable(this.getUserNameToCheck())) {
			this.inputStream = new ByteArrayInputStream(
					"{\"success\":true,\"message\":\"This username is available\"}"
							.getBytes("UTF8"));
		} else {
			this.inputStream = new ByteArrayInputStream(
					"{\"success\":false,\"message\":\"Username has already been taken\"}"
							.getBytes("UTF8"));
		}
		return SUCCESS;
	}
	// end ajax for checking username availablity
}
